package com.tinycomment.dbutils;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

import java.sql.SQLException;

import com.tinycomment.dbutils.DbType;

public abstract class SqlHelper {	
    private static SqlHelper helper = null;
    protected Connection connection = null;
    
    public static SqlHelper getInstance(){
		return new MySqlHelper();
	}
	
	public static SqlHelper getInstance(DbType type){
		SqlHelper helper = null;
		if(type.equals(DbType.Oracle)){
			helper = new OracleHelper();
		}else if(type.equals(DbType.MySql)){
			helper = new MySqlHelper();
		}
		return helper;
	}
	
    public static String ToString(Object o) {
        return o.toString();
    }

    public static int ToInt(Object o) {
        int val = Integer.parseInt(o.toString());
        return val;
    }

    public static Date ToDate(Object o) {
        return null;
    }
    
    public static long ToLong(Object o){
    	return Long.parseLong(o.toString());
    }

    public void DealParameter(PreparedStatement stmt, Parameter[] paraArray) throws SQLException {
        if (paraArray != null) {
            for (Parameter p : paraArray) {
                p.setParameter(stmt);
            }
        }
    }

    public void close() {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public Connection getConnection(){
        return this.connection;
    }
    //access methods
	public boolean ExecuteSql(String sql) {
		int result = 0;
		Statement stmt = null;
		try {
			stmt = connection.createStatement();
			result = stmt.executeUpdate(sql);
			stmt.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			this.close();
		}
		return result > 0;
	}

	public boolean ExecuteSql(String sql, Parameter[] paraArray) {
		int result = 0;
		PreparedStatement stmt = null;
		try {
			stmt = this.connection.prepareStatement(sql);
			this.DealParameter(stmt, paraArray);
			result = stmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			this.close();
		}
		return result > 0;
	}

	public ResultSet getResultSet(String sql) {
		String strQuery = sql;

		ResultSet rs = null;
		try {
			Statement stmtQuery = connection.createStatement();
			rs = stmtQuery.executeQuery(strQuery);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}

	public ResultSet getResultSet(String sql, Parameter[] paraArray) {
		ResultSet rs = null;
		try {
			PreparedStatement stmt = this.connection.prepareStatement(sql);
			this.DealParameter(stmt, paraArray);
			rs = stmt.executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}
}
